import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "nprogress";
import { dynamic } from "./dynamicRoutes";

interface RoutesItem {
  path: string;
  component?: any;
  name?: string;
  redirect?: string;
  children?: any;
}

// 总路由表
let routes: Array<RoutesItem> = [];
// 初始路由表
let fixedRoutes: Array<RoutesItem> = [
  {
    path: "/",
    name: "Index",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@view/user/login.vue"),
  },
  {
    path: "/403",
    name: "403",
    component: () => import("@view/exception/403/index.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("@view/exception/404/index.vue"),
  },
];
// 固定路由
let exceptionRoutes: RoutesItem = {
  path: "/:pathMatch(.*)*",
  name: "404",
  component: () => import("@view/exception/404/index.vue"),
};

routes = fixedRoutes;

// 导出路由
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  // 获取当前默认路由
  let ISTO = false;
  let currenRoutes = router.options.routes;
  for (let index = 0; index < currenRoutes.length; index++) {
    const element = currenRoutes[index];
    if (element.childrenpath) {
      if (element.childrenpath.indexOf(to.path) >= 0) {
        ISTO = true;
      }
    } else {
      if (element.path == to.path) {
        ISTO = true;
      }
    }
  }
  if (ISTO) {
    next();
  } else {
    // 异步路由
    let dynamicRouter = dynamic();
    let rou: RoutesItem;
    for (let index = 0; index < dynamicRouter.length; index++) {
      const element = dynamicRouter[index];
      if (element.childrenpath) {
        if (element.childrenpath.indexOf(to.path) >= 0) {
          rou = element;
        }
      } else {
        if (element.path == to.path) {
          rou = element;
        }
      }
    }
    if (rou && rou.path) {
      for (let index = 0; index < dynamicRouter.length; index++) {
        const element = dynamicRouter[index];
        currenRoutes.push(element);
        router.addRoute(element);
      }
      currenRoutes.push(exceptionRoutes);
      router.addRoute(exceptionRoutes);
      next({ ...to, replace: true });
    } else {
      next("/404");
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
